import { createRouter, createWebHashHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import store from "../store/index.js";
const routes = [
  {
    path: "/:pathMatch(.*)*",
    redirect: "/page404"
  },
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/page404",
    component: () => import('../components/404.vue')
  },
  {
    path: "/login",
    component: LoginView,
  },
  {
    path: '/home',
    component: () => import('../views/HomeView.vue'),
    redirect: '/asshole',
    children: [
      {
        path: '/asshole',
        component: () => import('../components/asshole.vue'),
      },
      {
        path: '/users',
        component: () => import('../components/users.vue'),
      },
      {
        path: '/roles',
        component: () => import('../components/roles.vue'),
      },
      {
        path: '/rights',
        component: () => import('../components/rights.vue'),
      },
      {
        path: '/reports',
        component: () => import('../components/reports.vue'),
      },
      {
        path: '/params',
        component: () => import('../components/params.vue'),
      },
      {
        path: '/goods',
        component: () => import('../components/goods.vue'),
      },
      {
        path: '/goods/all',
        component: () => import('../components/goodsAll.vue'),
      },
      {
        path: '/categories',
        component: () => import('../components/categories.vue'),
      },
      {
        path: '/orders',
        component: () => import('../components/orders.vue'),
      },
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  let token = window.sessionStorage.getItem("token")
  let menus = window.sessionStorage.getItem("menus")
  if (!token && to.path != "/login") {
    next("/login")
  }
  else if (menus) {
    menus = JSON.parse(menus)
    if (menus.indexOf(to.path) != -1) {
      if (to.path == "/goods/all") {
        window.sessionStorage.setItem("activePath", "/goods");
      } else {
        window.sessionStorage.setItem("activePath", to.path);
      }
      next()
    } else {
      next("/page404")
    }
  } else {
    next()
  }
})

export default router
